package com.takepoints.mobile;

import java.net.URLEncoder;

import com.takepoints.android.bo.CustomerSiteInfo;
import com.takepoints.android.bo.Promotion;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.vo.ReturnVal;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.StringUtil;

import com.takepoints.mobile.dialog.ImgPreviewDlg;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class TPPromoDetail extends BaseActivity {
	
	private int promoTypeId = 0;
	private int promoId = 0;
	private String picture;
	private String custSiteName = "";
	
	private final String IMG_URL = "https://www.takepoints.com/public/uploads/mobile/";
	private final String CUST_IMG_URL = "https://www.takepoints.com/public/uploads/cgallery/customer";
	// https://www.takepoints.com/public/uploads/cgallery/customer12585/_thumb_
	
	private Button btnTake = null;
	
	private Promotion promotion = null;
	private String[] custImages = null;
	private CustomerSiteInfo siteInfo = null;
	private String typeName = "โปรโมชั่น";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.promotiondetail);
        manageMenu(0);
    	
        Bundle bundle = this.getIntent().getExtras();
        try{
	        promoTypeId = Integer.valueOf(bundle.getString("promoTypeId"));
	        promoId = Integer.valueOf(bundle.getString("promoId"));
        } catch(Exception e){
        	e.printStackTrace();
        }
        try{
        	custSiteName = bundle.getString("custSiteName");
        } catch(Exception e){
        	e.printStackTrace();
        }
        picture = bundle.getString("picture");
        
        ImageView imgLogo = (ImageView)findViewById(R.id.imgLogo);
    	TextView lblHeader = (TextView)findViewById(R.id.lblHeader);
        if(promoTypeId == PublicServices.PROMOTION_TYPE_CARD){
	    	lblHeader.setText("รายละเอียดบัตรสะสมแสตมป์ส้ม");
	    	typeName = "บัตรสะสม";
	    	imgLogo.setImageResource(R.drawable.header_cards);
		} else if(promoTypeId == PublicServices.PROMOTION_TYPE_OFFER){
	    	lblHeader.setText("รายละเอียดคูปองส่วนลด");
	    	typeName = "คูปองส่วนลด";
	    	imgLogo.setImageResource(R.drawable.header_coupons);
		} else if(promoTypeId == PublicServices.PROMOTION_TYPE_REWARD){
	    	lblHeader.setText("รายละเอียดการแลกรางวัล");
	    	typeName = "รายการรางวัล";
	    	imgLogo.setImageResource(R.drawable.header_rewards);
		} else if(promoTypeId == PublicServices.PROMOTION_TYPE_DEAL){
	    	lblHeader.setText("รายละเอียด..ดีล");
	    	typeName = "ดีล";
	    	imgLogo.setImageResource(R.drawable.header_deal);
		}
        
    	ImageView imgPromotion = (ImageView)findViewById(R.id.imgPromotion);
    	if(imgPromotion != null){
			Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + picture);
			if(bitmap != null){
				imgPromotion.setImageBitmap(bitmap);
			} else{
				imgPromotion.setTag(IMG_URL + URLEncoder.encode(picture));
				new DownloadImageTask().execute(imgPromotion);
			}
		}

    	btnTake = (Button)findViewById(R.id.btnTake);
    	if( ( promoTypeId == PublicServices.PROMOTION_TYPE_CARD
			    			|| promoTypeId == PublicServices.PROMOTION_TYPE_OFFER
			    			|| promoTypeId == PublicServices.PROMOTION_TYPE_REWARD )
    				&& getSharedIntValue(TPConst.PRF_MEMBER_ID) > 0 ){
	    	btnTake.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
	    	btnTake.setOnClickListener(new View.OnClickListener(){
				 public void onClick(View view) {
					 confirmGetPromotionDlg();
				 }
	        });
    	} else{
    		//btnTake.setTextSize(13);
    		btnTake.setText("Takepoints");
    	}
        processDetail();
	}
	
	private void processDetail(){
		final ProgressDialog dialog = ProgressDialog.show(this, "Takepoints.com", "Loading Detail ...", true);
		final Handler handler = new Handler() {
        	public void handleMessage(Message msg) {
    	    	LinearLayout lnrContent = (LinearLayout)findViewById(R.id.lnrContent);
    	    	lnrContent.getBackground().setAlpha(200);
        	    if(promotion != null){
        	    	TextView lblHeader = (TextView)findViewById(R.id.lblHeader);
        	    	if(promoTypeId == PublicServices.PROMOTION_TYPE_DEAL){
        	    		lblHeader.setText("ใช้ดีล..ที่ " + promotion.getCustomerName() + " (" + promotion.getSiteName() + ")");
        	    	} else{
        	    		if(!StringUtil.isEmpty(custSiteName)){
        	    			lblHeader.setText(custSiteName);
        	    		} else{
        	    			lblHeader.setText(promotion.getCustomerName() + " (" + promotion.getSiteName() + ")");
        	    		}
        	    	}
        	    	TextView lblItemName = (TextView)findViewById(R.id.lblItemName);
        	    	lblItemName.setText(promotion.getTitleName());
        	    	lblItemName.setTextColor(Color.parseColor("#777777"));
        	        
        	    	TableRow tr1 = new TableRow(lnrContent.getContext());
        	    	tr1.setBackgroundResource(R.drawable.info_middle);
        	    	TableRow.LayoutParams tr1Param = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 50);
        	    	tr1Param.setMargins(0, 4, 0, 4);
        	    	tr1.setLayoutParams(tr1Param);
	        	    	TextView txtExpiryDate = new TextView(tr1.getContext());
	        	    	txtExpiryDate.setText("ภายในวันที่  " + promotion.getExpiryDate());
	        	    	txtExpiryDate.setTextSize(13);
	        	    	txtExpiryDate.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
	        	    	txtExpiryDate.setTextColor(Color.parseColor("#555555"));
	        	    	txtExpiryDate.setMinimumHeight(42);
	        	    	txtExpiryDate.setPadding(5, 5, 5, 3);
	        	    	txtExpiryDate.setGravity(Gravity.CENTER_VERTICAL);
	        	    tr1.addView(txtExpiryDate);
	        	    lnrContent.addView(tr1);
        	        
        	        TableRow tr2 = new TableRow(lnrContent.getContext());
        	        tr2.setBackgroundResource(R.drawable.info_middle);
        	    	TableRow.LayoutParams tr2Param = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
        	    	tr2Param.setMargins(0, 4, 0, 4);
        	    	tr2.setLayoutParams(tr2Param);
	        	        TextView txtOfferLine1 = new TextView(tr2.getContext());
	        	        txtOfferLine1.setText(promotion.getOfferLine1());
	        	        txtOfferLine1.setTextSize(11);
	        	        txtOfferLine1.setTextColor(Color.GRAY);
	        	        txtOfferLine1.setHeight(LayoutParams.WRAP_CONTENT);
	        	        txtOfferLine1.setPadding(5, 5, 5, 3);
	        	        txtOfferLine1.setSingleLine(false);
	        	        txtOfferLine1.setGravity(Gravity.TOP);
		        	tr2.addView(txtOfferLine1);
		        	lnrContent.addView(tr2);
    		        
		        	if(promoTypeId == 1 || promoTypeId == 2){
			        	LinearLayout rowCustAddr = new LinearLayout(lnrContent.getContext());
			        	rowCustAddr.setOrientation(LinearLayout.HORIZONTAL);
			        		TableLayout.LayoutParams tblCustAddrParam = new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, 63);
				        	tblCustAddrParam.setMargins(0, 4, 0, 6);
				        rowCustAddr.setLayoutParams(tblCustAddrParam);
				        
		        	        final Button btnAddress = new Button(rowCustAddr.getContext());
		        	        btnAddress.setBackgroundResource(R.drawable.button_info);
		        	        	LinearLayout.LayoutParams btnParam1 = new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.FILL_PARENT);
		        	        btnAddress.setLayoutParams(btnParam1);
		        	        btnAddress.setText("ที่อยู่ร้านค้า");
		        	        btnAddress.setTextSize(13);
		        	        btnAddress.setTextColor(Color.BLACK);
		        	        btnAddress.setPadding(5, 5, 5, 3);
		        	        btnAddress.setGravity(Gravity.CENTER);
		        	        btnAddress.setOnClickListener(new View.OnClickListener(){
		        	    		public void onClick(View view){
		        	    			StringBuilder infoStr = new StringBuilder("ที่อยู่ร้านค้า\n");
		        	    			if(!StringUtil.isEmpty(siteInfo.getAddress())){
		        	    				infoStr.append("\n" + siteInfo.getAddress());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getCity())){
		        	    				infoStr.append("\nเขต/อำเภอ  " + siteInfo.getCity());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getProvinceName())){
		        	    				infoStr.append("\nจังหวัด  " + siteInfo.getProvinceName());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getZipCode())){
		        	    				infoStr.append("\nรหัสไปรษณีย์  " + siteInfo.getZipCode());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getPhoneNumber())){
		        	    				infoStr.append("\nโทรศัพท์ " + siteInfo.getPhoneNumber());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getMobileNumber())){
		        	    				infoStr.append("\nมือถือ " + siteInfo.getMobileNumber());
		        	    			}
		        	    			if(!StringUtil.isEmpty(siteInfo.getFaxNumber())){
		        	    				infoStr.append("\nแฟ็กซ์ " + siteInfo.getFaxNumber());
		        	    			}
		        	    			alert(infoStr.toString());
		        	    		}
			    	        });
		        	        btnAddress.setOnTouchListener(new View.OnTouchListener(){
		        	    		public boolean onTouch(View v, MotionEvent event){
			    					int action = event.getAction();
			    					switch(action){
			    						case MotionEvent.ACTION_DOWN:
			    							btnAddress.setBackgroundResource(R.drawable.canvas_shadow);
			    					 		break;
			    					 	case MotionEvent.ACTION_UP:
			    					 		btnAddress.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	case MotionEvent.ACTION_MOVE:
			    					 		btnAddress.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	case MotionEvent.ACTION_CANCEL:
			    					 		btnAddress.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	default:
			    					 		break;
			    					}
		    						return false;
		        	    		}
		        	    	});
			        	rowCustAddr.addView(btnAddress);
		        	    
		        	        final Button btnLocate = new Button(rowCustAddr.getContext());
		        	        btnLocate.setBackgroundResource(R.drawable.button_info);
			        	        LinearLayout.LayoutParams btnParam2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
			        	        btnParam2.leftMargin = 4;
		        	        btnLocate.setLayoutParams(btnParam2);
		        	        btnLocate.setText("แผนที่ร้านค้า   >");
		        	        btnLocate.setTextSize(13);
		        	        btnLocate.setTextColor(Color.BLACK);
		        	        btnLocate.setPadding(5, 5, 5, 3);
		        	        btnLocate.setGravity(Gravity.CENTER);
		        	        btnLocate.setOnClickListener(new View.OnClickListener(){
		        	    		public void onClick(View view){
		        	    			if(siteInfo != null
		        	    					&& !StringUtil.isEmpty(siteInfo.getLatitude())
		        	    					&& !StringUtil.isEmpty(siteInfo.getLongtitude())){
			        	    			Intent nearByInt = new Intent(view.getContext(), NearBy.class);
			        	    			nearByInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			        	    			
			        	    			nearByInt.putExtra(TPConst.LOCATE_TYPE, TPConst.LOCATE_TYPE_SPECIFIC);
			        	    			nearByInt.putExtra("latParam", siteInfo.getLatitude());
			        	    			nearByInt.putExtra("longParam", siteInfo.getLongtitude());
			        	    			nearByInt.putExtra("siteName", siteInfo.getSiteName());
			        	    			
			        	    			startActivity(nearByInt);
		        	    			}
		        	    		}
			    	        });
		        	        btnLocate.setOnTouchListener(new View.OnTouchListener(){
		        	    		public boolean onTouch(View v, MotionEvent event){
			    					int action = event.getAction();
			    					switch(action){
			    						case MotionEvent.ACTION_DOWN:
			    							btnLocate.setBackgroundResource(R.drawable.canvas_shadow);
			    					 		break;
			    					 	case MotionEvent.ACTION_UP:
			    					 		btnLocate.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	case MotionEvent.ACTION_MOVE:
			    					 		btnLocate.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	case MotionEvent.ACTION_CANCEL:
			    					 		btnLocate.setBackgroundResource(R.drawable.button_info);
			    					 		break;
			    					 	default:
			    					 		break;
			    					}
		    						return false;
		        	    		}
		        	    	});
			        	rowCustAddr.addView(btnLocate);
		        	    
		        	    lnrContent.addView(rowCustAddr);
        	    	}
        	    }
        	    
        	    if(custImages != null && custImages.length > 0){
        	    	HorizontalScrollView hzView = new HorizontalScrollView(lnrContent.getContext());
        	    	hzView.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.FILL_PARENT, 120));
        	    	hzView.setPadding(0, 0, 0, 0);
        	    	hzView.setBackgroundResource(R.drawable.card_bg);
        	    	
        	    	LinearLayout trImg = new LinearLayout(hzView.getContext());
	        	    trImg.setPadding(1, 2, 1, 2);
	        	    trImg.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
	        	    int n = custImages.length;
	        	    for(int i=0; i<n; i++){
	        	    	final ImageView custImg = new ImageView(trImg.getContext());
        				
	        	    	final String imgPath = IMG_CACHE_PATH + promotion.getCustUserId() + "_thumb_" + URLEncoder.encode(custImages[i]);
        				final Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        				if(bitmap != null){
        					custImg.setImageBitmap(bitmap);
        				} else{
        					custImg.setTag( CUST_IMG_URL + promotion.getCustUserId()
								  	  	  + "/" + "_thumb_" + URLEncoder.encode(custImages[i]));
        					new DownloadImageTask().execute(custImg);
        				}
        				
	        	    	custImg.setPadding(2, 2, 2, 2);
	        	    	custImg.setScaleType(ScaleType.FIT_XY);
		        	    	LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(128, 116);
		        	    	lp.setMargins(3, 1, 3, 1);
	        	    	custImg.setLayoutParams(lp);
	        	    	custImg.setBackgroundResource(R.drawable.image_border);
	        	    	custImg.setOnClickListener(new View.OnClickListener(){
	        	    		public void onClick(View view){
	        	    			ImgPreviewDlg dlg = new ImgPreviewDlg(view.getContext());
	        	    			dlg.setTitle(promotion.getTitleName());
	        	    			
	        	    			if(bitmap != null){
	        	    				dlg.setImgSdPath(imgPath);
	        	    			} else{
	        	    				dlg.setImgUrl(custImg.getTag().toString());
	        	    			}
	        	    			dlg.show();
	        	    		}
		    	        });
	        	    	trImg.addView(custImg);
	        	    }
	        	    hzView.addView(trImg);
	        	    
	        	    lnrContent.addView(hzView);
        	    }
        		dialog.dismiss();
        	}
		};
        Thread thread = new Thread(){
        	public void run(){
        		promotion = PublicServices.getPromotionDetail(promoId);
        		if(promotion != null){
        			if(!StringUtil.isEmpty(promotion.getCustId())){
        				custImages = PublicServices.getCustImages(promotion.getCustId());
        			}
        			if(!StringUtil.isEmpty(promotion.getPrimarySiteId())){
        				siteInfo = PublicServices.getSiteInfoBySiteId(promotion.getPrimarySiteId());
        				if(siteInfo != null){
	        				//promotion.setCustomerName(siteInfo.getCustName());
	        				promotion.setSiteName(siteInfo.getSiteName());
        				}
        			}
        		}
        		handler.sendEmptyMessage(0);
        	}
        };
        thread.start();
	}
	
	protected void confirmGetPromotionDlg(){
		AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage("คุณต้องการบันทึก" + typeName + "นี้ ใช่หรือไม่ ?");
		alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				processGetPromotion();
			}
		});
		alertbox.setNeutralButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				dlgInf.dismiss();
			}
		});
		alertbox.show();
    }
	
	private ReturnVal result = null;
	
	private void processGetPromotion(){
		final ProgressDialog dialog = ProgressDialog.show(this, "Takepoints.com", "กำลังบันทึก" + typeName + " ...", true);
		final Handler handler = new Handler(){
        	public void handleMessage(Message msg){
        		if(result != null && !StringUtil.isEmpty(result.getTrxCode())){
        			alert("บันทึก" + typeName + " เรียบร้อยแล้ว");
    			} else{
    				if(result.getMessage() != null && !"null".equalsIgnoreCase(result.getMessage().trim())){
    					alert(result.getMessage());
    				} else{
            			alert("ไม่สามารถบันทึก" + typeName + "นี้ !");
    				}
    			}
        		dialog.dismiss();
        	}
		};
		Thread thread = new Thread(){
        	public void run(){
        		try{
	        		result = PublicServices.savePromotion( getSharedStringValue(TPConst.PRF_USRNAME), getSharedStringValue(TPConst.PRF_PASSWD)
	        											 , promoId, getSharedIntValue(TPConst.PRF_MEMBER_ID));
        		} catch(Exception e){
        			popup(e.getMessage());
        		}
        		handler.sendEmptyMessage(0);
        	}
        };
        thread.start();
	}
	
}
